//
//  IncomeCostDetailViewController.swift
//  HuaYun
//
//  Created by enghou on 2018/11/26.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

import UIKit
import WebKit
import SnapKit
class IncomeCostDetailViewController: BaseViewController,WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler {
    
    var plantype = "0"
    var orgCode = ""
    var source: [JSON] = []
    override func path(for name: String) -> String {
        return IncomeAndCostPlan
    }
    
    override var names: Array<String>{
        get{
            return ["haha"]
        }
    }
    
    override func param(for name: String) -> Dictionary<String, Any> {
        return ["planType": plantype,"orgCode": orgCode]
    }
    
    override func success(for name: String) -> NetSuccess {
        func suc(json: JSON)->Void{
            if let success = json.contents?["success"]?.bool {
                if success == true  {
                    if let data = json.contents?["data"]?.array {
                        source = data
                        let config = WKWebViewConfiguration.init()
                        config.preferences = WKPreferences.init()
                        config.preferences.minimumFontSize = 10;
                        config.preferences.javaScriptEnabled = true
                        config.preferences.javaScriptCanOpenWindowsAutomatically = false
                        config.userContentController = WKUserContentController.init()
                        config.processPool = WKProcessPool.init()
                        webView = WKWebView.init(frame: CGRect.zero, configuration: config)
                        webView.uiDelegate = self
                        webView.navigationDelegate = self
                        self.view.addSubview(webView)
                        if let path = Bundle.main.path(forResource: "details", ofType: "html") {
                            do{
                                let str = try String.init(contentsOf: URL.init(fileURLWithPath: path))
                                webView.loadHTMLString(str, baseURL: nil)
                            }catch{
                                print(error)
                            }
                        }
                        config.userContentController.add(self, name: "getdata()")
                    }
                    
                }
            } else {
                alert(json.contents?["errorMsg"]?.rawString())
            }
        }
        return suc
    }
    
    override func method(for name: String) -> NetMethod {
        return .get
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)


    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
    }
    
    var webView: WKWebView = WKWebView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.load(with: self.names[0])
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        get{
            return UIInterfaceOrientation.landscapeLeft
        }
    }
    
    override var shouldAutorotate: Bool{
        get{
            return true
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get{
            return UIInterfaceOrientationMask.landscapeLeft
        }
    }
    
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        do {
            var array: Array<Dictionary<String,Any>> = []
            for item in source {
                let budget = item.contents?["budget"]?.int ?? 0
                
                let deptName = item.contents?["deptName"]?.rawString() ?? ""
                let orgCode = item.contents?["orgCode"]?.rawString() ?? ""
                let planMoney = item.contents?["planMoney"]?.int ?? 0
                let projContract = item.contents?["projContract"]?.int ?? 0
                let projInvoice = item.contents?["projInvoice"]?.int ?? 0
                let projPayment = item.contents?["projPayment"]?.int ?? 0
                let subentry = item.contents?["subentry"]?.rawString() ?? ""
                let dic = ["budget":budget,"deptName": deptName,"orgCode": orgCode,"planMoney": planMoney,"projContract": projContract,"projInvoice": projInvoice,"projPayment":projPayment,"subentry":subentry] as [String : Any]
                array.append(dic)
            }

            let data = try JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
            let str = String.init(data: data, encoding: .utf8)
            let script = "getdata(" + str! + ")"
            webView.evaluateJavaScript(script) { (result, error) in
                if error == nil {
                    self.alert("成功")
                } else {
                    self.alert("失败")
                }
            }
            
        } catch {
            
        }
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message)
    }
    
    func headlabel(text :String)->UILabel {
        let bumen = UILabel()
        bumen.text = text
        bumen.textColor = .white
        bumen.font = UIFont.systemFont(ofSize: 14)
        bumen.textAlignment = .center
        return bumen
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
